package com.yide.myworld.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yide.myworld.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author d
 * @date 2023/3/30 10:02
 */
@Slf4j
@Service
public class WeChatAppletService {
    /**
     * 小程序 appId
     */
    @Value("${wechat.applet.appid:null}")
    private String appid;

    /**
     * 小程序 appSecret
     */
    @Value("${wechat.applet.secret:null}")
    private String secret;

    /**
     * 小程序登录
     * @param jsCode
     * @return
     */
    public String weChatLogin(String jsCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";

        url = url + "?appid=" + appid + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        //请求zego服务端
        return commonWeChatLogin(url);
    }

    private String commonWeChatLogin(String url) {
        String json;
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            httpClient = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            log.info("-----httpGet-----" + httpGet);
            HttpResponse response = httpClient.execute(httpGet);
            log.info("-----HttpResponse---response----" + response);
            json = EntityUtils.toString(response.getEntity(), "utf-8");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 获取token
     * @return
     */
    public String getWechatToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret=" + secret;
        // 获取微信access_token
        return commonWeChatLogin(url);
    }


    /**
     * 获取手机号
     * @param code
     * @throws Exception
     */
    public String getPhoneNumber(String code,String accessToken) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+accessToken;
        //设置请求的参数
        List<NameValuePair> nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("code", code));
        return commonGetPhoneNumber(url,nvps);
    }

    /**
     * 小程序的appid
     * @return
     */
    public String getAppid(){
        return appid;
    }



    private String commonGetPhoneNumber(String url,List<NameValuePair> nvps) {
        String json;
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            JSONObject jsonObject = new JSONObject();
            for (NameValuePair nvp : nvps) {
                jsonObject.put(nvp.getName(), nvp.getValue());
            }
            String param = jsonObject.toString();
            StringEntity stringEntity = new StringEntity(param, "utf-8");
            stringEntity.setContentType("text/json");

            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            json = EntityUtils.toString(response.getEntity(), "utf-8");

            log.info("响应:[{}]",json);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        WeChatAppletService weChatAppletService = new WeChatAppletService();

        String code = "0c1UfkGa19Fz3F0ZapIa1SRrjX3UfkGj";
        String mcode = "bbcb3b7cd8f2befe90572211968baaf295aaae3506539a56da25714b52cc1251";


        //获取token
        String wechatToken = weChatAppletService.getWechatToken();
        System.out.println("----wechatToken----"+wechatToken);
        Object sessionKeyToken = JSON.parseObject(wechatToken).get("access_token");
        System.out.println("---sessionKeyToken-----"+sessionKeyToken);
        //获取手机号
        String phoneNumbers = weChatAppletService.getPhoneNumber(mcode, String.valueOf(sessionKeyToken));
        if ("0".equals(JSON.parseObject(phoneNumbers).get("errcode"))){

        }
        System.out.println("----phoneNumber----"+phoneNumbers);
        Object queryPhoneNumber = JSON.parseObject(phoneNumbers).get("purePhoneNumber");
        System.out.println("----queryPhoneNumber----"+queryPhoneNumber);
        //获取openId
        String openId = weChatAppletService.weChatLogin(code);
        System.out.println("---openId-----"+openId);


    }








}
